<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class OrderController extends Controller
{
    //生成订单
    public function add(Request $request)
    {	
    	$title = '提交订单';
    	//会话跟踪
    	$user = $request -> session() ->  get('user');
      
    	//友情链接
        $link = DB::table('bro_link') -> orderBy('order', 'desc') -> get();
        //========获取收货人地址=======
       	$address= DB::table('bro_address') -> where('status',1) ->where('uid',$user -> id) -> first();
       	if(empty($address))
       	{
       		//如果 无默认地址 选最早的一条
       		$address = DB::table('bro_address') -> where('status',0) ->where('uid',$user -> id) -> take(1) -> first();
       		if(!empty($address))
       		{
            //获取剩余地址
            $address2 = DB::table('bro_address') -> where('status',0) ->where('uid',$user -> id) -> whereNotIn('id',[$address -> id]) -> get();
          // dd($address);
          }
       	}else{
       		//=====获取不是默认地址
       		$address2 = DB::table('bro_address') -> where('status',0) -> where('uid',$user -> id) -> get();
       	}

      
    	if(empty($address2))
      {
        $address2 = '';
        return view('home.order.order',['title' => $title,'user' => $user,'link' => $link,'address' => $address,'address2' => $address2]);
      }else{
        return view('home.order.order',['title' => $title,'user' => $user,'link' => $link,'address' => $address,'address2' => $address2]);
      }
    }

    //添加地址
    public function insert(Request $request)
    {	
    	$data = $request -> except('_token');
    	$user = $request -> session() ->  get('user');
    	$data['uid'] = $user -> id;
    	//=====添加收货地址=======
    	$res = DB::table('bro_address') -> insert($data);
    	
    	return response() -> json($res);	
    }
    //改变默认地址
    public function change(Request $request)
    {
    	$id = $request ->all();
      $user = $request -> session() ->  get('user');
      $data['status'] = 0;
    	
      $res = DB::table('bro_address') -> where('uid',$user -> id) -> update($data);
      
      $a = DB::table('bro_address') -> where('id',$id) -> update(['status' => 1]);
      return response() -> json($a);
    }
    //删除地址
    public function delete(Request $request)
    {
      $id = $request -> all();

      $res = DB::table('bro_address') -> where('id',$id) -> delete();
      return response() -> json($res);

    }
    
}
